package calao.client;

import com.google.gwt.core.client.GWT;

import calao.client.i18n.CoreEventText;
import calao.client.i18n.EventText;
import calao.client.ui.Format;
import calao.client.ui.SortableGrid;

public class HistoryPanel
extends SortableGrid
{
	
	final static EventText coreText = (CoreEventText)GWT.create(CoreEventText.class);
	
	final Desktop desktop;
	
	EventLog[] eventLogs = new EventLog[0];
	
	HistoryPanel(Desktop desktop)
	{
		super(3);
		this.desktop = desktop;
		setHeader(0, desktop.text.date());
		setColumnFormat(0, Format.DATE_AND_TIME);
		setHeader(1, desktop.text.user());
		setHeader(2, desktop.text.event());
		desktop.sessionService.getPreviousEvents(0, 30, new ServiceCallback() {
			public void onReturn(Object result) {
				show((EventLog[])result);
			}
		});
	}
	
	void show(EventLog[] eventLogs)
	{
		this.eventLogs = eventLogs;
		refresh();
	}

	protected Object getData(int row, int col) 
	{
		EventLog eventLog = eventLogs[row];
		switch (col) {
		case 0:
			return new Long(eventLog.getTimeMinutes()*60000L);
		case 1:
			return new Long(eventLog.getGlobalUserId());
		case 2:
			return buildMessage(eventLog);
		}
		throw new IllegalArgumentException();
	}
	
	String buildMessage(EventLog log)
	{
		EventText text = coreText;
		if (log.appName!=null) text = desktop.getApplicationEventText(log.appName);
		if (text==null) return "";
		StringBuffer buffer = new StringBuffer();
		String pattern = text.getString(log.eventName);
		if (pattern==null) return "";
		int pos = 0;
		for (;;) {
			int newPos = pattern.indexOf('%');
			if (newPos==-1) {
				buffer.append(pattern.substring(pos));
				break;
			}
			newPos++;
			if (newPos==pattern.length()) {
				buffer.append('%');
				break;
			}
			char c = pattern.charAt(newPos);
			if (c=='%') buffer.append('%');				
			else {
				int num = Character.digit(c, 10);
				String arg = num<log.argv.length? log.argv[num] : null;
				if (arg!=null) buffer.append(arg);
			}
			newPos++;
			if (newPos==pattern.length()) break;
			pos = newPos;
		}
		return buffer.toString();
	}

	protected int getRowCount() 
	{
		return eventLogs.length;
	}

}
